package com.x52im.rainbowchat.http.dao;

import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.dbpool.DBDepend;
import com.eva.framework.dbpool.DBShell;
import com.x52im.rainbowchat.http.logic.dto.UserRegisterDTO;
import com.x52im.rainbowchat.http.util.ip.IPSeeker;
import com.x52im.rainbowchat.http.util.ip._Utils;

import java.util.Vector;

/**
 * 用户相关操作
 */
public class UserDAO {
    DBShell db = new DBShell();

    /**
     * 插入用户
     */
    public boolean insertUser(UserRegisterDTO registerDTO, String ip) throws Exception {
        Vector sqls = new Vector();
        Vector values = new Vector();
        sqls.add("INSERT INTO missu_users(user_mail, phone,nickname,user_psw,user_sex,register_ip,user_regieon,register_time) " +
                "VALUES(?,?,?,?,?,?,?," + DBDepend.getDefaultDatetimeFunc() + ")");
        values.add(new Object[]{
                registerDTO.getUser_phone() + "@email.com",
                registerDTO.getUser_phone(),
                registerDTO.getNickname(),
                CommonUtils.encyptPassword(registerDTO.getUser_psw(), ""),
                registerDTO.getUser_sex(),
                ip,
                _Utils.checkChinaArea(IPSeeker.getInstance().getCountry(ip))}
        );
        return db.update(sqls, values, true);
    }

    public boolean updateUserPsw(String phone, String newPsw) throws Exception {
        String sql = "UPDATE missu_users SET user_psw=? WHERE phone=?";
        boolean b = db.update(sql, new Object[]{CommonUtils.encyptPassword(newPsw, ""), phone}, true);
        return b;
    }

    public boolean updatePayPsw(String phone, String payPsw) throws Exception {
        String sql = "UPDATE missu_users SET pay_psw=? WHERE phone=?";
        boolean b = db.update(sql, new Object[]{CommonUtils.encyptPassword(payPsw, ""), phone}, true);
        return b;
    }

    public String queryUserRealName(String userUid) throws Exception {
        return db.querySingleItem("is_realname", "missu_users", "user_uid=" + userUid);
    }

    /**
     * 查询用户
     */
    public String queryUserByPhone(String phone) throws Exception {
        return db.querySingleItem("user_uid", "missu_users", "phone='" + phone + "'");
    }

    /**
     * 查询用户
     */
    public String queryUserByEmail(String email) throws Exception {
        return db.querySingleItem("user_uid", "missu_users", "user_mail='" + email + "'");
    }
}
